from flask_socketio import SocketIO, send, emit, join_room, leave_room
from network.NetworkModel_pb2 import RoomChatMessage, FeedItem
from utils import RedisOperation
from flask import Flask
from gevent import monkey
import config


def create_app():
    app = Flask(__name__)
    app.config.from_object(config)
    return app


monkey.patch_socket()
app = create_app()
socketio = SocketIO(app=app, async_mode='gevent', message_queue='redis://')


@socketio.on('connect')
def on_connect():
    send('connect')


@socketio.on('message')
def on_message(data):
    message = RoomChatMessage()
    message.ParseFromString(data)
    room = message.ruid
    emit('message', data, room=room)
    print('message')


@socketio.on('join')
def on_join(data):
    message = RoomChatMessage()
    message.ParseFromString(data)
    room = message.ruid
    join_room(room)
    emit('join', data, room=room)
    print('join')


@socketio.on('leave')
def on_leave(data):
    message = RoomChatMessage()
    message.ParseFromString(data)
    room = message.ruid
    leave_room(room)
    emit('leave', data, room=room)
    print('leave')


@socketio.on('alive')
def on_alive(data):
    print('alive')
    item = FeedItem()
    item.ParseFromString(data)
    rdm = RedisOperation(db=int(item.fid))
    item_data = rdm.get_data(item.ruid)
    if item_data is None:
        rdm.set_data(item.ruid, data, 60)
    else:
        rdm.set_data(item.ruid, item_data, 60)


if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=8888)
